package com.codechen.scaffold.books.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.codechen.scaffold.books.constant.Constants;
import com.codechen.scaffold.books.domain.entity.Book;
import com.codechen.scaffold.books.domain.entity.BookWithUser;
import com.codechen.scaffold.books.domain.entity.LendRecord;
import com.codechen.scaffold.books.domain.req.BookQueryRequest;
import com.codechen.scaffold.books.domain.req.BookRentQueryRequest;
import com.codechen.scaffold.books.service.IBookService;
import com.codechen.scaffold.books.service.IBookWithUserService;
import com.codechen.scaffold.books.service.ILendRecordService;
import com.codechen.scaffold.common.domain.Result;
import com.codechen.scaffold.common.domain.UserInfo;
import com.codechen.scaffold.common.exception.BusinessException;
import com.codechen.scaffold.common.holder.UserInfoHolder;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Calendar;
import java.util.Date;
import java.util.Objects;

/**
 * @author : wuweihong
 * @desc : TODO  请填写你的功能描述
 * @date : 2025-06-19
 */

@RestController
@RequestMapping("/bookrent")
@Api(tags = "书籍借阅管理")
public class BookRentController {

	@Autowired
	private IBookWithUserService bookWithUserService;

	@Autowired
	private IBookService bookService;


	@ApiOperation(value = "书籍借阅")
	@PostMapping("/rent/{bookId}")
	public Result rentBook(@PathVariable("bookId") Long bookId) {
		Book book = bookService.getById(bookId);
		if (book.getBorrownum() >= book.getTotal()) {
			throw new BusinessException(500, "本书已全部被借阅!!!");
		}
		UserInfo userInfo = UserInfoHolder.getUserInfo();
		BookWithUser bookWithUser = bookWithUserService.lambdaQuery()
				.eq(BookWithUser::getBookId, bookId)
				.eq(BookWithUser::getUserId, userInfo.getUserId()).one();
		if (Objects.nonNull(bookWithUser)) {
			if (bookWithUser.getProlong() >= Constants.MAX_PRO_LONG_COUNT) {
				throw new BusinessException(500, "你已经达到续借上限，请先归还");
			}
		}else {
			bookWithUser = new BookWithUser();
			bookWithUser.setBookName(book.getName());
			bookWithUser.setBookId(bookId);
			bookWithUser.setIsbn(book.getIsbn());
			bookWithUser.setUserId(userInfo.getUserId());
			bookWithUser.setNickName(userInfo.getUserNickName());
			bookWithUser.setLendtime(new Date());
			bookWithUser.setStatus(0);
		}
		bookWithUser.setProlong(Objects.nonNull(bookWithUser.getProlong()) ? bookWithUser.getProlong() + 1 :  1);
		Date deadTime = bookWithUser.getDeadtime();
		if (Objects.isNull(deadTime)) {
			deadTime = new Date();
		}
		// 增加3天
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(deadTime);
		calendar.add(Calendar.DAY_OF_MONTH, Constants.MAX_RENT_DAY); // 负数表示减天数
		Date newDate = calendar.getTime();
		bookWithUser.setDeadtime(newDate);
		bookWithUserService.saveOrUpdate(bookWithUser);
		book.setBorrownum(book.getBorrownum()+1);
		return Result.success(null);
	}

	@ApiOperation(value = "书籍归还")
	@PostMapping("/return/{bookId}")
	public Result returnBook(@PathVariable("bookId") Long bookId) {
		UserInfo userInfo = UserInfoHolder.getUserInfo();
		BookWithUser bookWithUser = bookWithUserService.lambdaQuery()
				.eq(BookWithUser::getBookId, bookId)
				.eq(BookWithUser::getUserId, userInfo.getUserId()).one();
		if (Objects.nonNull(bookWithUser)) {
			bookWithUser.setActualReturnDate(new Date());
			bookWithUser.setStatus(1);
			bookWithUserService.saveOrUpdate(bookWithUser);
		}
		return Result.success(null);
	}

	@ApiOperation(value = "书籍借阅列表")
	@PostMapping("/pageList/{pageNo}/{pageSize}")
	public Result list(@PathVariable(value = "pageNo") Long pageNo,
	                   @PathVariable(value = "pageSize") Long pageSize,
	                   @RequestBody BookRentQueryRequest bookQueryRequest) {
		Page<BookWithUser> page = new Page<>(pageNo, pageSize);
		IPage<BookWithUser> newsBaseVOIPage = bookWithUserService.queryList(page, bookQueryRequest);
		return Result.success(newsBaseVOIPage);
	}

}
